package com.taichuan.selfcheck.ui.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.eventbus.McuUpdateProgressEvent;
import com.taichuan.selfcheck.eventbus.McuVersionEvent;
import com.taichuan.selfcheck.hardware.mcuUpdate.McuUpdateManager;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.serialcommunication.SerialPortPublic;
import com.taichuan.serialcommunication.mcuUpdate.base.BaseMcuUpdateClient;
import com.taichuan.tcutils.taichuan.SystemUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2022/2/17
 */
public class McuUpdateFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {
   private static final String TAG = McuUpdateFragment.class.getSimpleName();

   /**
    * Handler事件类型 刷新单片机程序升级Dialog
    */
   private static final int WHAT_REFRESH_MCU_UPDATE_PROGRESS_DIALOG = 1;

   @BindView(R.id.mcu_version_textView)
   TextView mcuVersionTv;
   @BindView(R.id.android_version_textView)
   TextView androidVersionTv;
   @BindView(R.id.device_type_textView)
   TextView deviceTypeTv;
   @BindView(R.id.update_file_dir_textView)
   TextView updateFileDirTv;
   @BindView(R.id.update_file_name_textView)
   TextView updateFileNameTv;

   ResultDialog resultDialog;

   private String updateFailureReason;

   /**
    * 定义一个Dialog用于显示单片机程序升级流程
    */
   private ProgressDialog mcuUpdateProgressDialog;

   @Override
   protected void getBundleValues(Bundle bundle) {

   }

   @Override
   protected int setContentViewId() {
      return R.layout.fragment_mcu_update;
   }

   @Override
   protected void initView(View view, Bundle bundle) {
      EventBus.getDefault().register(this);

      resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_4, getResources().getString(R.string.sd_card_and_usb_test), getContext());

      //获取单片机版本号
      SerialPortPublic.getSpiVersion();

      initConfig();
   }

   private void initConfig() {
      androidVersionTv.setText(SystemUtils.getSystemVersion());
      deviceTypeTv.setText(SystemUtils.getTcDeviceType().name());

      McuUpdateManager.get().init(getActivity());
      BaseMcuUpdateClient mcuUpdateClient = McuUpdateManager.get().getMcuUpdateClient();
      if (mcuUpdateClient != null){
         updateFileDirTv.setText(mcuUpdateClient.getMcuUpdateFileAssetsDir());
         updateFileNameTv.setText(mcuUpdateClient.getMcuUpdateFileAssetsName());
      }

   }

   @Subscribe(threadMode = ThreadMode.MAIN)
   public void onReceiveMcuVersionEvent(McuVersionEvent event){
      mcuVersionTv.setText(event.getMcuVersion());
   }

   @Override
   public void onDestroyView() {
      super.onDestroyView();
      EventBus.getDefault().unregister(this);
   }

   @OnClick({R.id.check_mcu_update_by_local_apk_button})
   @Override
   protected void onXmlClick(View v) {
      super.onXmlClick(v);
      switch (v.getId()){
         case R.id.check_mcu_update_by_local_apk_button:{
            if (SystemUtils.isSupportMcuUpdate()){
               BaseMcuUpdateClient mcuUpdateClient = McuUpdateManager.get().getMcuUpdateClient();
               if (mcuUpdateClient != null){
                  BaseMcuUpdateClient.McuUpdateState mcuUpdateState = McuUpdateManager.get().getMcuUpdateState();
                  Log.i(TAG, "onXmlClick: 执行单片机升级前 升级管理类的状态为： " + mcuUpdateState.name());

                  if (mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_INIT ||
                          mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_VERSION_LATEST ||
                          mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_UPDATE_PACKAGE_NOT_EXIST ||
                          mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_UPDATE_FAILURE ||
                          mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_UPDATE_PROCESS_ERROR ||
                          mcuUpdateState == BaseMcuUpdateClient.McuUpdateState.STATE_UPDATE_SUCESS) {
                     McuUpdateManager.get().main(mcuUpdateStateListener);
                  } else {
                     showMsg("单片机升级流程无需执行或正在执行中,请稍后再尝试");
                  }
               }else {
                  showMsg("该机型还未实现单片机升级功能，无法使用");
               }
            }else {
               showMsg("该机型不支持单片机升级功能，无法使用");
            }


            break;
         }
      }
   }

   private BaseMcuUpdateClient.OnMcuUpdateStateListener mcuUpdateStateListener =
           new BaseMcuUpdateClient.OnMcuUpdateStateListener() {
      @Override
      public void onMcuUpdateResult(BaseMcuUpdateClient.McuUpdateState state, String resultMsg) {
         Log.e(TAG, "onMcuUpdateResult: 单片机程序升级流程执行结果的状态为：  " + state + "  原因：  " + resultMsg);
         updateFailureReason = resultMsg;
      }

      @Override
      public void onMcuUpdateProgress(boolean isSendSucess, int currentPackageCount, int totalPackageCount, BaseMcuUpdateClient.McuUpdateState currentUpdatestate) {
         Log.e(TAG, "onMcuUpdateProgress: 单片机程序升级正在执行，当前进度： " + currentPackageCount + "  / " + totalPackageCount + "  是否发送升级包完毕：  " + isSendSucess);
         handler.sendMessage(handler.obtainMessage(
                 WHAT_REFRESH_MCU_UPDATE_PROGRESS_DIALOG,
                 new McuUpdateProgressEvent(isSendSucess, currentPackageCount, totalPackageCount, currentUpdatestate)));

      }
   };

   private Handler handler = new Handler(new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {
         switch (msg.what){
            case WHAT_REFRESH_MCU_UPDATE_PROGRESS_DIALOG: {      //单片机升级进度Dialog
               McuUpdateProgressEvent event = (McuUpdateProgressEvent) msg.obj;
               Log.e(TAG, "dispatchMessage: 接收到单片机程序升级事件：  " + event.toString());
               if (event != null) {
                  //如果Dialog没初始化则进行初始化
                  if (mcuUpdateProgressDialog == null) {
                     mcuUpdateProgressDialog = new ProgressDialog(getActivity());
                     mcuUpdateProgressDialog.setTitle("硬件功能升级");
                     mcuUpdateProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                     mcuUpdateProgressDialog.setCancelable(false);
                     mcuUpdateProgressDialog.setCanceledOnTouchOutside(false);
                  }

                     mcuUpdateProgressDialog.setMax(event.getTotalPackageCount());
                     mcuUpdateProgressDialog.setProgress(event.getCurrentPackageCount());
                     if (!event.isSendSucess()) { //升级包数据还未发送成功时
                        mcuUpdateProgressDialog.setMessage("设备正在进行硬件功能升级，将暂停提供服务，请耐心等待");
                        mcuUpdateProgressDialog.show();
                     } else {
                        if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_UPDATING) {
                           mcuUpdateProgressDialog.setMessage("设备硬件功能升级完毕，即将重启设备");
                        } else if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_UPDATE_FAILURE) {
                           mcuUpdateProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                           mcuUpdateProgressDialog.setMessage("设备硬件功能升级失败，请尽快联系物业处理");
                           mcuUpdateProgressDialog.show();
                        }else if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_UPDATE_PACKAGE_NOT_EXIST){
                           showMsg("本地apk中不存在单片机升级包，无法执行升级！");
                        }else if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_VERSION_LATEST){
                           showMsg("无需更新，设备的单片机程序版本已为最新");
                        }else if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_MCU_VERSION_LATEST){
                           showMsg("无需更新，设备的单片机程序版本已为最新");
                        }else if (event.getMcuUpdateState() == BaseMcuUpdateClient.McuUpdateState.STATE_UPDATE_PROCESS_ERROR){
                           showMsg("单片机升级流程执行异常，结束更新" + "\n" + "原因： " + updateFailureReason);
                        }
                     }
               }
               break;
            }
         }
         return false;
      }
   });

   @Override
   protected EmptyPresenter createPresenter() {
      return new EmptyPresenter();
   }

   @Override
   protected boolean isAllowAutoFinishFragment() {
      return false;
   }

   @Override
   public void doOnAutoFinishFragment() {
      resultDialog.show();
   }
}
